package game.zqll;

import com.artemis.BaseSystem;
import com.artemis.World;
import com.artemis.WorldConfigurationBuilder;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.kotcrab.vis.ui.VisUI;
import game.zqll.mod.ModContainer;
import game.zqll.mod.ModLoader;
import game.zqll.mod.ModMeta;
import game.zqll.systems.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.artemis.WorldConfigurationBuilder.Priority.HIGH;

public class ModSampleApplication extends ApplicationAdapter {

    // 核心ECS世界
    private World world;
    private WorldConfigurationBuilder configBuilder;
    private AssetManager assetManager;
    public static final int worldWidth = 600;
    public static final int worldHeight = 480;

    @Override
    public void create() {
        // 初始化ECS世界
        VisUI.load();
        OrthographicCamera camera = new OrthographicCamera();
        configBuilder = new WorldConfigurationBuilder()
            .with(new Mappers())
            .with(new CameraSystem(camera))
            .with(new SpawnSystem())
            .with(new MoveSystem())
            .with(HIGH, new ClearScreenSystem())
            .with(new BorderRenderSystem())
            .with(new GuiSystem())
        ;
        assetManager = new AssetManager();
        initializeAndLoadGameMod(configBuilder, assetManager);

        world = new World(configBuilder.build().register("camera", camera));

        for (BaseSystem system : world.getSystems()) {
            System.out.println("注册了系统: " + system.getClass().getName());
        }
    }

    private void initializeAndLoadGameMod(WorldConfigurationBuilder configBuilder, AssetManager assetManager) {
        // 读取 mods列表
        final Map<String, ModContainer> modIdMap = ModLoader.scanMods();
        // 读取 ModsConfig.conf
        List<String> activeMods = ModLoader.readActiveMods();
        final List<ModContainer> activeModsHandled = new ArrayList<>();
        if (activeMods != null && !activeMods.isEmpty()) {
            // 加载 activeMods 里的 mod
            for (String modId : activeMods) {
                ModContainer c = modIdMap.get(modId);
                if (c != null) {
                    activeModsHandled.add(c);
                }
            }
        }

        for (ModContainer container : activeModsHandled) {
            ModMeta meta = container.meta;
            if (meta.dependencies != null && !meta.dependencies.isEmpty()) {
                for (ModMeta.Dependency dep : meta.dependencies) {
                    if (dep.modId == null || dep.modId.isEmpty()) continue;
                    if (!modIdMap.containsKey(dep.modId)) {
                        System.err.printf("[依赖检测] Mod [%s] 缺少依赖: %s\n", meta.modId, dep.modId);
                    } else {
                        // 可扩展：版本号校验
                        if (dep.version != null && !dep.version.isEmpty()) {
                            String actualVersion = modIdMap.get(dep.modId).meta.version;
                            if (actualVersion == null || !actualVersion.equals(dep.version)) {
                                System.err.printf("[依赖检测] Mod [%s] 依赖 %s 版本不匹配，需: %s，实际: %s\n", meta.modId, dep.modId, dep.version, actualVersion);
                            }
                        }
                    }
                }
            }
        }

        // 初始化
        for (ModContainer container : activeModsHandled) {
            GameMod mod = container.modInstance;
            mod.initialize(configBuilder);
            mod.loadResources(assetManager);
        }
    }

    @Override
    public void render() {
        // 启动游戏循环
        world.setDelta(Gdx.graphics.getDeltaTime());
        world.process();
    }

    @Override
    public void resize(int width, int height) {
        world.getSystem(CameraSystem.class).getViewport().update(width, height, true);
        world.getSystem(GuiSystem.class).getStage().getViewport().update(width, height, true);
    }
}
